<template>
  <div class="myDiamonds">
    <!-- 头部 -->
    <div class="header_wrap">
      <CommonHeader :balance="gemsNum" />
    </div>
    <!-- 我的钻石 -->
    <div class="my_diamond_top">
      <img src="@/assets/images/ic_star_72@2x.png" class="diamond_72_img" />
      <div class="detail" @click="goDeatils">
        <div class="num">My Gems</div>
        <div class="bold_wrod">x{{ gemsNum }}</div>
      </div>
    </div>
    <!-- 钻石列表 -->
    <div class="diamond_list">
      <div class="item_block" v-for="(item, index) in selectList" :key="index"
        :class="{ activeItem: index === activeIndex }" @click="selectItem(index)">
        <div class="price_d">
          <span class="price_d_pre" v-if="item.oldPrice" style="text-decoration: line-through;">${{ item.oldPrice
          }}</span>
          <img src="@/assets/images/ic_money_arrow_b@2x.png" v-if="item.oldPrice" />
          <span class="price_d_last">${{ item.newPrice }}</span>
        </div>
        <div class="price_yuan">
          <span class="number">{{ item.num }}</span>
          <img src="@/assets/images/ic_star_32@2x.png" />
        </div>
        <div class="first_item_top" v-if="index === 0">
          <div class="time_block">
            <img src="@/assets/images/ic_time@2x.png" />
            <!-- 倒计时显示 -->
            <van-count-down :time="1800000" format="HH:mm:ss" class="time_text" />
          </div>
          <div class="first_item_top_right">90% OFF</div>
        </div>
      </div>
    </div>
    <van-button type="primary" class="comfirmBtn" @click="debouncedSubmit">Continue</van-button>
    <p class="text_p">For payment issues, please <span @click="contactUs">contact us</span></p>
    <!-- 宝石说明 -->
    <div class="exp_wrap">
      <div class="spc_line"></div>
      <p class="title">diamond description</p>
      <p class="detail">
        Gems are virtual goods provided by AI Creator that can be used to access all platform
        features.
      </p>
      <p class="detail second_p">
        Gems do not expire after purchase but cannot be withdrawn or transferred.
      </p>
    </div>
    <!-- 宝石消耗规则 -->
    <div class="rule_wrap">
      <div class="tile">Diamond consumption rules</div>
      <div class="rule_detail">
        <div class="block block_fisrt">
          <div>Features</div>
          <div>Member</div>
        </div>
        <div class="block">
          <div>AI Remove</div>
          <div>
            <span class="text">100</span>
            <img src="@/assets/images/ic_star_24@2x.png" class="img" />
            <span class="text">per time</span>
          </div>
        </div>
        <div class="block">
          <div>AI Pose</div>
          <div>
            <span class="text">100</span>
            <img src="@/assets/images/ic_star_24@2x.png" class="img" />
            <span class="text">per time</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 支持的支付方式 -->
    <div class="suport_pay_way" v-if="false">
      <div class="title">We Accept</div>
      <ul class="ul">
        <li v-for="(item, index) in 9" :key="index">
          <img src="@/assets/images/paypal@2x.png" />
        </li>
      </ul>
    </div>
    <!-- 宝石详情页面 -->
    <DiamondsDetails v-if="false" />
  </div>
</template>

<script setup>
import { startLoading, endLoading } from "../utils/loading";
import DiamondsDetails from "@/components/DiamondsDetails.vue";
import CommonHeader from "@/components/CommonHeader.vue";
import { useRouter } from "vue-router";
import { ref, onMounted, reactive, inject } from "vue";
import api from "@/api";
import { getStripe } from '@/utils/stripe';
import { trackEvent } from '@/utils/firebase';
import { useDebounce } from '@/utils/useDebounce'


const router = useRouter();
// 注入App.vue提供的queryOrderTime方法
// const queryOrderTime = inject('queryOrderTime');

const gemsNum = ref("199");

// 选择购买方案
const selectList = reactive([
  { oldPrice: "119.96", newPrice: "59.98", num: "29999" },
  { oldPrice: "", newPrice: "29.98", num: "5999" },
  { oldPrice: "", newPrice: "19.98", num: "1999" },
  { oldPrice: "", newPrice: "9.98", num: "499" },
]);

const contactUs = () => {
  router.push("/supportCenter");
}

const goDeatils = () => {
  router.push("/diamondsDetails");
};

const activeIndex = ref(0);

const selectItem = (index) => {
  activeIndex.value = index;
};

// 支付
const redirectToCheckout = async () => {
  trackEvent('点击购买', { id: '10002', wf_id: '', type: '', type1: '1' });//埋点
  const prevRoute = JSON.parse(sessionStorage.getItem('prevRoute'));
  const referrerUrl = prevRoute ? prevRoute.fullPath : '/';
  // console.log('地址:',referrerUrl)
  // 创建订单
  const selectAmount = selectList[activeIndex.value].num;
  try {
    const res = await api.orderCreate({
      amount: Number(selectAmount)
    });
    localStorage.setItem('amount', selectAmount);
    if (res.code !== 200) {
      trackEvent('创建订单失败', { id: '100016', type: '', error_code: '' });//埋点
    }
    // 时间
    // if (queryOrderTime) {
    //   queryOrderTime(); // 执行App.vue中的方法
    // }
    // 获取订单详情
    queryOrderDetail({ orderId: res.data.orderId })
    // 获取会话
    const getClickId = localStorage.getItem('click_id')
    stripeSession({ orderId: res.data.orderId, returnUrl: encodeURIComponent(referrerUrl), clickId: getClickId, ct: 'checkout' }) // 对returnUrl进行编码
    trackEvent('发起支付', { id: '100015', type1: '1' });//埋点
  } catch (err) {
    console.log(err);
    trackEvent('创建订单失败', { id: '100016', type: '', error_code: '' });//埋点
  }
};

// 防抖调用
const debouncedSubmit = useDebounce(redirectToCheckout, 0)

// 订单详情
const queryOrderDetail = async (params) => {
  try {
    const res = await api.orderDetail(params);
  } catch (err) {
    console.log(err);
  }
};

// 会话
const stripeSession = async (params) => {
  try {
    const res = await api.stripeSession(params);
    toCheckout(res.data.publicKey, res.data.sessionId)
  } catch (err) {
    console.log(err);
  }
};

const toCheckout = async (publicKey, sessionId) => {
  startLoading()
  try {
    const stripe = await getStripe(publicKey);
    endLoading();
    // 使用 Stripe SDK 提供的跳转方法
    const { error } = await stripe.redirectToCheckout({
      sessionId: sessionId
    });
    if (error) {
      console.error('跳转失败:', error);
    }
  } catch (err) {
    console.error('Stripe 加载失败:', err);
    endLoading()
  }
};

// 查询积分余额
const queryBalance = async () => {
  try {
    const res = await api.pointsBalance();
    gemsNum.value = String(res.data.balance);
  } catch (err) {
    console.log(err);
  }
};

onMounted(() => {
  queryBalance();
});
</script>

<style scoped lang="less">
.myDiamonds {
  min-height: 100vh;
  box-sizing: border-box;
  padding: 70px 16px 30px 16px;
  /* 背景图设置 */
  background-image: url("../assets/images/bg_texture@2x.png");
  background-position: top center;
  /* 从顶部开始 */
  background-repeat: no-repeat;
  /* 不重复 */
  background-size: 100% auto;
  /* 宽度满屏，高度自适应 */
  background-color: #fbfbfd;

  .my_diamond_top {
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin-top: 16px;

    .diamond_72_img {
      width: 72px;
    }

    .detail {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      box-sizing: border-box;
      height: 72px;

      .num {
        font-size: 16px;
        color: rgba(0, 0, 0, 0.45);
        line-height: 16px;
      }

      .bold_wrod {
        font-weight: 600;
        font-size: 32px;
        line-height: 38px;
        color: rgba(0, 0, 0, 0.95);
      }
    }
  }

  .diamond_list {
    padding: 8px;
    margin-top: 16px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 0.45);
    box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.45);
    border-radius: 12px;

    .item_block {
      width: 160px;
      height: 95px;
      background: linear-gradient(180deg,
          rgba(255, 255, 255, 0.85) 0%,
          rgba(255, 255, 255, 0.45) 100%);
      border-radius: 8px;
      position: relative;
      margin-bottom: 8px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .price_d {
        font-size: 15px;
        color: rgba(0, 0, 0, 0.45);
        text-align: center;

        display: flex;
        justify-content: center;
        align-items: center;

        .price_d_pre {
          font-size: 15px;
          color: rgba(0, 0, 0, 0.45);
        }

        .price_d_last {
          font-size: 15px;
          color: rgba(0, 0, 0, 0.95);
        }

        img {
          width: 8px;
          margin-left: 4px;
          margin-right: 4px;
        }
      }

      .price_yuan {
        display: flex;
        justify-content: center;
        align-items: center;

        .number {
          font-size: 23px;
          color: rgba(0, 0, 0, 0.95);
          font-weight: 700;
        }

        img {
          width: 32px;
          margin-left: 4px;
        }
      }

      .first_item_top {
        width: 100%;
        height: 20px;
        position: absolute;
        left: 0;
        top: -23px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .time_block {
          display: flex;
          justify-content: center;
          align-items: center;
          background: linear-gradient(90deg, #ffd52f 0%, #f874ff 50%, #516eff 100%);
          padding: 0 5px;

          img {
            width: 12px;
          }

          .time_text {
            font-size: 11px;
            color: #ffffff;
            margin-left: 4px;


          }
        }

        .first_item_top_right {

          background: #516eff;
          font-size: 11px;
          color: #ffffff;
          padding: 1px 5px;
        }
      }
    }

    .activeItem {
      border: 1.06667vw solid;
      border-image: linear-gradient(90deg, rgba(255, 213, 47, 1), rgba(248, 116, 255, 1), rgba(81, 110, 255, 1)) 4 4;
    }
  }

  .comfirmBtn {
    width: 100%;
    height: 64px;
    background: linear-gradient(90deg, #ffd52f 0%, #f874ff 50%, #516eff 100%);
    box-shadow: 0px 4px 4px 0px rgba(0, 20, 244, 0.16);
    border-radius: 8px 8px 8px 8px;
    border: 0;
    margin-top: 16px;

    :deep(.van-button__text) {
      font-size: 20px;
      color: #ffffff;
      font-weight: 700;
    }
  }

  .text_p {
    margin-top: 15px;
    text-align: center;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.95);
    line-height: 18px;

    span {
      color: #6251ff;
      text-decoration: underline;
    }
  }

  .exp_wrap {
    padding: 0 8px;
    margin-top: 40px;
    margin-bottom: 4px;
    position: relative;

    .spc_line {
      width: 100vw;
      height: 1px;
      background: rgba(0, 0, 0, 0.25);
      position: absolute;
      top: -24px;
      left: -16px;
    }

    .title {
      font-size: 16px;
      color: rgba(0, 0, 0, 0.95);
      line-height: 18px;
      font-weight: 700;
    }

    .detail {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.75);
      line-height: 18px;
      margin-top: 8px;
    }

    .second_p {
      margin-top: 16px;
    }
  }

  .rule_wrap {
    margin-top: 20px;
    padding: 0 8px;

    .tile {
      font-weight: 700;
      font-size: 16px;
      color: rgba(0, 0, 0, 0.95);
      line-height: 18px;
      margin-bottom: 8px;
    }

    .rule_detail {
      padding: 10px 0;

      .block {
        display: flex;
        height: 42px;
        line-height: 42px;
        justify-content: space-between;
        background: rgba(0, 0, 0, 0.05);

        div {
          display: block;
          flex: auto;
          color: rgba(0, 0, 0, 0.95);
          font-size: 13px;
          text-align: center;
          display: flex;
          justify-content: center;
          align-items: center;

          .text {
            font-size: 13px;
            color: rgba(0, 0, 0, 0.95);
          }

          .img {
            width: 16px;
          }
        }

        div:firs-child {
          width: 96px;
        }
      }

      .block_fisrt {
        background: rgba(0, 0, 0, 0.1);
        border-radius: 4px 4px 0 0;
      }
    }
  }

  .suport_pay_way {
    margin-top: 24px;
    box-sizing: border-box;
    padding: 0 8px;

    //padding-bottom: 150px;
    .title {
      font-size: 15px;
      color: rgba(0, 0, 0, 0.95);
      line-height: 18px;
      font-weight: 600;
    }

    .ul {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: wrap;

      li {
        width: 33.33%;
        height: 40px;
        margin-top: 8cqi;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          width: 87px;
        }
      }
    }
  }
}
</style>
